package repository.relsys.app;

import java.io.File;

import java.io.FileNotFoundException;

import org.apache.log4j.Logger;
import repository.relsys.config.*;
import org.simpleframework.xml.Serializer;
import org.simpleframework.xml.core.Persister;

public class Settings {

	private Logger logger = Logger.getLogger(this.getClass().getName());

	private final String configFile = "config/config.xml";

	public Config config;

	private static class SettingsHolder {
		private static final Settings INSTANCE = new Settings();
	}

	public static Settings getInstance() {
		return SettingsHolder.INSTANCE;
	}

	/**
	 * 
	 *
	 */
	private Settings() {
		try {

			Serializer serializer = new Persister();
			File source = new File(Thread.currentThread()
					.getContextClassLoader().getResource(configFile).getFile());

			config = serializer.read(Config.class, source);

			logger.info("Settings loaded!");

		} catch (FileNotFoundException fnfe) {
			fnfe.printStackTrace();
			logger.error(
					"Could not open the configuration file: " + configFile,
					fnfe);

		} catch (Exception e) {
			e.printStackTrace();
			logger.error("Could not serialize the configuration file: "
					+ configFile, e);
		}
	}

	public void refresh() {
		try {

			Serializer serializer = new Persister();
			File source = new File(Thread.currentThread()
					.getContextClassLoader().getResource(configFile).getFile());

			config = serializer.read(Config.class, source);

			logger.info("Settings re-loaded!");

		} catch (FileNotFoundException fnfe) {
			fnfe.printStackTrace();
			logger.error(
					"Could not open the configuration file: " + configFile,
					fnfe);

		} catch (Exception e) {
			e.printStackTrace();
			logger.error("Could not serialize the configuration file: "
					+ configFile, e);
		}
	}
}
